package com.chushouya.manager.service.api.impl;

import cn.hutool.core.util.IdUtil;
import com.chushouya.common.support.Contexts;
import com.chushouya.common.constant.ActivityStatusEnum;
import com.chushouya.manager.dto.admin.activity.ActivityQuery;
import com.chushouya.manager.dto.api.bonus.UserExchangeDTO;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Numbers;
import com.general.framework.core.lang.Validate;
import com.chushouya.manager.dao.entity.ActivityEntity;
import com.chushouya.manager.dao.entity.BonusTypeEntity;
import com.chushouya.manager.dao.entity.BonusUserEntity;
import com.chushouya.manager.dao.repository.ActivityRepository;
import com.chushouya.manager.dao.repository.BonusTypeRepository;
import com.chushouya.manager.dao.repository.BonusUserRepository;
import com.chushouya.manager.dto.admin.bonus.ReceiveBonusDTO;
import com.chushouya.manager.dto.admin.bonustype.BonusTypeQuery;
import com.chushouya.manager.service.api.ActivityLogService;
import com.chushouya.manager.service.api.ReceiveBonusService;
import com.google.common.base.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ReceiveBonusServiceImpl implements ReceiveBonusService {

    @Resource
    private ActivityRepository activityRepository;

    @Resource
    private BonusTypeRepository bonusTypeRepository;

    @Resource
    private BonusUserRepository userBonusRepository;

    @Resource
    private ActivityLogService activityLogService;


    private ActivityEntity getActivityById(Long activityId){
        ActivityEntity activityEntity = activityRepository.selectByPrimaryKey(activityId);
        Validate.isNull(activityEntity, "活动不存在");
        return activityEntity;
    }


    @Override
    public void userReceiveBonus(ReceiveBonusDTO receiveBonusDTO) {
        final Long activityId = receiveBonusDTO.getActivityId();
        final Long userId = Contexts.getUserContext().getUserId();

        //判断领取逻辑
        this.handleReceiveBonus(activityId,userId);

        ActivityEntity activityEntity = getActivityById(receiveBonusDTO.getActivityId());
        final String ActivityPrize = activityEntity.getActivityPrize();
        final String appId = Contexts.getHeaderContext().getAppId();
        final String platform = receiveBonusDTO.getPlatform();
        BonusTypeQuery bonusTypeQuery = new BonusTypeQuery();
        List<Long> typeIds = Jsons.parseArray(ActivityPrize, Long.class);
        bonusTypeQuery.setTypeIdList(typeIds);

        List<BonusTypeEntity> bonusTypeEntityList = bonusTypeRepository.selectList(bonusTypeQuery);
        List<BonusUserEntity> userBonusEntityList = new ArrayList<>();
        for (BonusTypeEntity bonusType:bonusTypeEntityList) {
            BonusUserEntity bonusUserEntity = buildUserBonus(bonusType, userId);
            userBonusEntityList.add(bonusUserEntity);
            bonusTypeRepository.updateSendNumber(bonusType.getTypeId(), Numbers.INTEGER_ONE);
        }
        userBonusRepository.insertList(userBonusEntityList);
        activityLogService.addActivityLog(activityId,activityEntity.getActivityName(), activityEntity.getActivityPrize(),activityEntity.getActivityType(),platform,appId);
    }

    @Override
    public void userExchangeBonus(UserExchangeDTO userExchangeDTO) {
        final String ticketNo = userExchangeDTO.getTicketNo();
        ActivityQuery activityQuery = new ActivityQuery();
        activityQuery.setTicketNo(ticketNo);
        ActivityEntity activityEntity = activityRepository.selectOne(activityQuery);
        if (Objects.equal(activityEntity.getStatus(), ActivityStatusEnum.USED.value())) {
            throw new IllegalArgumentException("该兑换码已被使用");
        }
        //已被使用
        ReceiveBonusDTO receiveBonusDTO = new ReceiveBonusDTO();
        receiveBonusDTO.setActivityId(activityEntity.getActivityId());
        receiveBonusDTO.setPlatform(userExchangeDTO.getPlatform());
        this.userReceiveBonus(receiveBonusDTO);
        ActivityEntity updateActivity = new ActivityEntity();
        updateActivity.setActivityId(activityEntity.getActivityId());
        updateActivity.setStatus(ActivityStatusEnum.USED.value());
        activityRepository.updateByPrimaryKeySelective(updateActivity);
    }

    /**
     * 领取逻辑
     */
    private void handleReceiveBonus(Long activityId,Long userId) {
        Validate.isTrue(activityLogService.isJoinActivity(activityId,userId), "已经参加过活动");
        //判断成交才能领取
//        switch (activityId.intValue()) {
//            case 100003:
//                Integer completeNumber1 = activityApiService.completeOrderNumber(Contexts.getUserContext().getUserId());
//                Validate.isTrue(completeNumber1 < 1, "您近一年内完成订单次数不足");
//                break;
//            case 100004:
//                Integer completeNumber2 = activityApiService.completeOrderNumber(Contexts.getUserContext().getUserId());
//                Validate.isTrue(completeNumber2 < 2, "您近一年内完成订单次数不足");
//                break;
//        }

    }

    private BonusUserEntity buildUserBonus(BonusTypeEntity bonusType, Long userId) {
        BonusUserEntity userBonus = new BonusUserEntity();
        final String appId = Contexts.getHeaderContext().getAppId();
        final Date nowTime = Dates.getTimeNow();
        final Integer useDay = bonusType.getUseDay();
        final Date startTime = Dates.getTimeNow();
        userBonus.setUserId(userId);
        userBonus.setMinAmount(bonusType.getMinAmount());
        userBonus.setBonusType(bonusType.getBonusType());
        userBonus.setTypeName(bonusType.getTypeName());
        userBonus.setTypeMoney(bonusType.getTypeMoney());
        userBonus.setTicketNo(IdUtil.getSnowflakeNextIdStr());
        userBonus.setTypeId(bonusType.getTypeId());
        userBonus.setStartTime(startTime);
        userBonus.setEndTime(Dates.addDays(startTime,useDay));
        userBonus.setOrderId(Numbers.LONG_ZERO);
        userBonus.setAppId(appId);
        userBonus.setCreateTime(nowTime);
        userBonus.setUpdateTime(nowTime);
        return userBonus;
    }




}
